package com.hmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.ai.AiModelInvoker;
import com.hmall.ai.CozeWorkflowClient;
import com.hmall.common.utils.UserContext;
import com.hmall.domain.po.Datas;
import com.hmall.domain.po.Datas2;
import com.hmall.domain.vo.DataVO;
import com.hmall.mapper.DataMapper;
import com.hmall.service.IDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HBQ
 * @since 2025-10-22
 */
@Service
public class DataServiceImpl extends ServiceImpl<DataMapper, Datas> implements IDataService {

    @Autowired
    private DataMapper dataMapper;

    @Autowired
    private AiModelInvoker aiModelInvoker;

    @Autowired
    private CozeWorkflowClient cozeWorkflowClient;

    @Override
    public String answerQuestion(String mbti, String hobby, String xingzuo) {
        String prompt = String.format("请基于对方的以下人设信息，生成1句贴合其特质、让对方感到被理解的聊天问候词（15-30字）：\n" +
                "对方MBTI人格类型：%s（贴合该人格沟通偏好，E人适配热情主动语气，I人适配温和不施压语气）\n" +
                "对方兴趣爱好：%s（自然融入兴趣相关元素，让对方感受到你关注其喜好，无需强行展开）\n" +
                "对方星座：%s（轻度结合星座温和特质，增加亲切感，不涉及迷信表述）\n" +
        "要求：口语化、无模板感，语气适配对方人设，带轻微互动感（如好奇式提问、共情式表达），不输出不符合对方人设的生硬问候。不能有任何解析，直接输出对话的话语", mbti, hobby, xingzuo);
        String answer = aiModelInvoker.DoubaoInvoker(prompt);
        return answer;
    }


    @Override
    public DataVO uploadData(Datas datas) throws IOException {
        LambdaQueryWrapper<Datas> queryWrapper = new LambdaQueryWrapper<Datas>();
        queryWrapper.eq(Datas::getUserId, UserContext.getUser());
        Long id = UserContext.getUser();
        if (getOne(queryWrapper) == null){
            dataMapper.saveData(datas, id);
        } else {
            dataMapper.updateData(datas, id);
        }
        String input = datas.toString();
        Pattern pattern = Pattern.compile("=(.*?)(,|\\))");
        Matcher matcher = pattern.matcher(input);

        List<String> resultList = new ArrayList<>();

        // 循环提取所有值并添加到List
        while (matcher.find()) {
            // group(1) 表示提取第一个分组（即value部分）
            resultList.add(matcher.group(1).trim());
        }
        String jsonStr = cozeWorkflowClient.runWorkflow(resultList);
        try {
            // 创建Jackson的ObjectMapper
            ObjectMapper objectMapper = new ObjectMapper();

            // 解析JSON为Map（键为字段名，值为对应数据）
            Map<String, Object> jsonMap = objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});

            // 提取"output"字段对应的数组，转换为List<String>
            List<String> outputList = objectMapper.convertValue(
                    jsonMap.get("output"),
                    new TypeReference<List<String>>() {}
            );

            // 打印结果（动态适应任意长度）
            System.out.println("提取的列表：" + outputList);
            System.out.println("列表长度：" + outputList.size());
            // 遍历元素
            for (String item : outputList) {
                System.out.println(item);
                DataVO one = dataMapper.getQuery(item);
                if (one != null){
                    return one;
                }
                return null;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Page<Datas2> pageQuery(Integer pageNum) {
        int pageSize = 3;  // 每页3条
        // 使用MyBatis Plus的标准分页方式
        IPage<Datas2> page = new Page<>(pageNum, pageSize);
        return dataMapper.pageQuery(page);
    }
}
